package com.sxt.demo.djiapplication.view

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.sxt.demo.djiapplication.R
import com.sxt.demo.djiapplication.utils.ToastUtils
import com.xuexiang.xfloatview.XFloatView

class FlightDataFloatView(context: Context) : XFloatView(context) {

    lateinit var velocityViewHolder: VelocityViewHolder

    lateinit var electricViewHolder: ElectricViewHolder

    private var isViewShow = false

    override fun getLayoutId(): Int = R.layout.flight_data

    override fun canMoveOrTouch(): Boolean = true

    override fun initFloatView() {
        velocityViewHolder = VelocityViewHolder(
                findViewById(R.id.velocity_x),
                findViewById(R.id.velocity_y),
                findViewById(R.id.velocity_z)
        )
        electricViewHolder = ElectricViewHolder(
                findViewById(R.id.voltage),
                findViewById(R.id.current),
        )
    }

    override fun initListener() {
//        setOnFloatViewClickListener {
//            ToastUtils.show("点击悬浮窗")
//        }
    }

    override fun isAdsorbView(): Boolean = false

    private fun applyFloatWindowPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val activity = context as AppCompatActivity
            activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (!Settings.canDrawOverlays(activity)) {
                    ToastUtils.show("缺少应用运行的悬浮窗权限")
                } else {
                    this@FlightDataFloatView.show()
                }
            }.launch(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${activity.packageName}")))
        }
    }

    override fun show() {
        if(isViewShow)  {
            this.dismiss()
            isViewShow = false
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                applyFloatWindowPermission()
                return
            }
        }
        isViewShow = true
        super.show()
    }

    inner class VelocityViewHolder(
            val velocityX: TextView,
            val velocityY: TextView,
            val velocityZ: TextView
    )

    inner class ElectricViewHolder(
            val voltage: TextView,
            val current: TextView
    )
}